<?php

use my\Security;
use think\Db;
use phpmailer\PHPMailer;

error_reporting(E_ERROR | E_PARSE );
/*
 * curl操作
 */
function https_request($url, $data = null) {
	$curl = curl_init ();
	curl_setopt ( $curl, CURLOPT_URL, $url );
	curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
	if (! empty ( $data )) {
		curl_setopt ( $curl, CURLOPT_POST, 1 );
		curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
	}
	curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
	$output = curl_exec ( $curl );
	curl_close ( $curl );
	return $output;
}

/**
 * 维数组排序
 * @param  [type] $arr  二维数组
 * @param  [type] $keys 所要排序的二维数组的建
 * @param  string $type
 * @return [type]       [description]
 */
function array_sort($arr,$keys,$type='desc'){ //2维数组排序
	 $keysvalue = $new_array = array();
	 foreach ($arr as $k=>$v){
	  $keysvalue[$k] = $v[$keys];
	 }
	 if($type == 'asc'){
	  asort($keysvalue);
	 }else{
	  arsort($keysvalue);
	 }
	 reset($keysvalue);
	 foreach ($keysvalue as $k=>$v){
	  $new_array[$k] = $arr[$k];
	 }
	 return $new_array;
}

/*
 * 根据坐标获取地方信息
 */
function get_info_by_local($local,$uid='',$order_type = 1){
	$url="http://restapi.amap.com/v3/geocode/regeo?key=".config("GD")."&location=".$local."&poitype=&radius=&extensions=all&batch=false&roadlevel=0";

	if($uid){
		$res_url = https_request($url);
		$res_url = json_decode($res_url,true);
		$adcode =  $res_url["regeocode"]["addressComponent"]['adcode'];
		$region_info = Db::name('region')->where('region_code',$adcode)->find();
		if( strstr($region_info['region_name'], '区')){
			$region_id = $region_info['parent_id'];
		}else{
			$region_id = $region_info['region_id'];
		}
		$coupon_arr = Db::name('coupon as c')->field('c.*')->join('region r','c.region_id=r.region_id','LEFT')->where('c.uid',$uid)->where('c.is_use','2')->where('c.order_type',$order_type)->where('c.end_time','>=',time())->where('r.region_id',$region_id)->select();
		return $coupon_arr;

	}else{
		return https_request($url);
	}
}

/*
 * 根据距离计算价格
 * @$total计价标准
 * @$distance 行驶距离
 * @return array
 * */
function calculatePrice($total,$distance){
	$total = unserialize($total);
	$sum = 0;//价格
	$i = 0;
	foreach ($total as $k => $v) {
		//$k 范围区间5000-8000m  $v单价 1.2元/km
		$dis = explode("-", $k);
		if ($dis[1] < $distance) {
			if ($i == 0) {
				$sum = $v;
			} else {
				$sum += ($dis[1] - $dis[0])/1000 * $v;
			}
		} else {
			if ($i == 0) {
				$sum = $v;
			} else {
				$sum += ($distance - $dis[0]) / 1000 * $v;
			}
			break;
		}
		$i++;
	}
	$sum = sprintf("%.1f", $sum)*100;
	return array("status" => 1, 'price' => $sum, 'distance' => $distance);
}
/*
check手机号码
*/

function isMobile( $text = '' ) {
    $search = '/^0?1[2|3|4|5|6|7|8|9][0-9]\d{8}$/';
    if ( preg_match( $search, $text ) ) {
        return ( true );
    } else {
        return ( false );
    }

}

/**
 * 处理列表搜索的二维数组
 * @param $data
 * @param $controller
 * @return array|false
 * */
function decode_array_2($data,$controller = ''){
	if(!empty($data)){
		$encode_field = $controller == 'inter'?config('inter_encode_field'):config('encode_field');
		foreach ($data as $key => $value) {
			foreach($value as $k=>$v){
				if(in_array($k,$encode_field)){
					$data[$key][$k] = Security::decrypt($v);
				}
				elseif(strpos($k,'time')!==false){
					$data[$key][$k] = $v?date('Y-m-d H:i:s',$v):'';
				}
				elseif(strpos($k,'_at')!==false){
					$data[$key][$k] = $v?date('Y-m-d',$v):'';
				}
				elseif($k=='auth_status'){
					$data[$key][$k] = $controller=='coach' ?auth_status_coach()[$v]:auth_status()[$v];
				}
				elseif($k=='order_status'){
					$data[$key][$k] = $controller=='bus'?bus_order_status()[$v]:order_status()[$v];
				}
				elseif($k=='ticket_status'){
					$data[$key][$k] = $controller=='bus'?bus_ticket_status()[$v]:$v;
				}
				elseif($k=='invoice_status'){
					$data[$key][$k] = invoice_status()[$v];
				}
				elseif($k=='pay_type'){
					$data[$key][$k] = pay_type()[$v];
				}
				elseif($k=='lost_goods_type'){
					$data[$key][$k] = get_lost_type()[$v];
				}
				elseif($k=='breakdown_type'){
					$data[$key][$k] = get_breakdown_type()[$v];
				}
				elseif($k=='passenger_type'){
					$data[$key][$k] = $controller=='bus'?bus_passenger_type()[$v]:$v;;
				}
				elseif($k=='id_type'){
					$data[$key][$k] = id_type()[$v];
				}
                elseif($k=='order_type'){
                    $data[$key][$k] = order_type()[$v];
                }
                elseif($k=='auth_type'){
                    $data[$key][$k] = auth_type()[$v];
                }

				if($v===null||$v===''){
					$data[$key][$k] = '';
				}
			}
		}
		return $data;
	}
	return false;
}

/**
 * 处理详情搜索的一维数组
 * @param $data
 * @param $controller
 * @return array|false
 * */
function decode_array($data,$controller = ''){
	if(!empty($data)){
		$encode_field = $controller=='inter'?config('inter_encode_field'):config('encode_field');
		foreach ($data as $key => $value) {
			if(in_array($key,$encode_field/*Define::ENCODE_FIELDS*/)){
                $data[$key] = Security::decrypt($value);//empty($controller)? Security::decrypt($value):$value;;
			}
			elseif(strpos($key,'time')){
				$data[$key] = $value?date('Y-m-d',$value):'';
			}
			elseif(strpos($key,'_at')){
				$data[$key] = $value?date('Y-m-d',$value):'';
			}
			elseif($key=='auth_status'){
				$data[$key] = $controller=='coach' ?auth_status_coach()[$value]:auth_status()[$value];
			}
			elseif($key=='order_status'){
				$data[$key] = $controller=='bus'?bus_order_status()[$value]:order_status()[$value];
			}
			elseif($key=='ticket_status'){
				$data[$key] = $controller=='bus'?bus_ticket_status()[$value]:$value;
			}
			elseif($key=='invoice_status'){
				$data[$key] = invoice_status()[$value];
			}
			elseif($key=='pay_type'){
				$data[$key] = pay_type()[$value];
			}
			elseif($key=='lost_goods_type'){
				$data[$key] = get_lost_type()[$value];
			}
			elseif($key=='breakdown_type'){
				$data[$key] = get_breakdown_type()[$value];
			}
			elseif($key=='passenger_type'){
				$data[$key] = $controller=='bus'?bus_passenger_type()[$value]:$value;;
			}
			elseif($key=='id_type'){
				$data[$key] = id_type()[$value];
			}
            elseif($key=='order_type'){
                $data[$key] = order_type()[$value];
            }
			elseif($key=='goods_pic'){
				$data[$key] = unserialize($value);
			}
			if($value===null||$value===''){
				$data[$key] = '';
			}
		}
		return $data;
	}
	return false;
}

/**
 * 加密需要保存的数据
 * @param $data
 * @param $controller  //识别需要加密的字段
 * @return array|false
 * */
function encode_data($data,$controller = '')
{
	if(empty($data)){
		return false;
	}
	$encode_field = $controller=='inter'?config('inter_encode_field'):config('encode_field');
	foreach ($data as $key => $val){
		if(in_array($key,$encode_field)){
			$data[$key] = Security::encrypt($val);
		}
	}
	return $data;
}

function auth_status($key = ''){
    $result = array(
		0=>'未认证',1=>'已认证',2=>'审核中',3=>'未通过',
	);
    if($key !== ''){
        return $result[$key];
    }else{
        return $result;
    }
}

function auth_type($key = ''){
	$result = array(
		0=>'未认证',1=>'快车',2=>'出租车',3=>'城际拼车',4=>'顺风车',5=>'私人运营车辆'
	);
    if($key !== ''){
        return $result[$key];
    }else{
	    return $result;
    }
}

function get_car_img_column(){
	return array(
		'license'=>'驾驶证',
		'permit'=>'行驶证',
		'taxi'=>'车辆运输证',
		'taxi_certificate'=>'服务资格证',
		'id_front'=>'身份证正面',
		'id_back'=>'身份证反面',
		'id_hold'=>'手持身份证图',
		'body_img'=>'车身图',
	);
}
function fr_get_car_img_column(){
	return array(
		'license'=>'驾驶证',
		'permit'=>'行驶证',
		'id_front'=>'身份证正面',
		'id_back'=>'身份证反面',
		'body_img'=>'车身图',
	);
}

/**
 * 支付方式
 * */
function pay_type($key=''){
	$data = array(
		1=>'支付宝',2=>'微信',3=>'余额'//,4=>'余额+支付宝',5=>'余额+微信',
	);
	if($key){
	    return $data[$key];
    }else{
	    return $data;
    }
}

/*
 * 发送站内信息
 */
function sendinfo($member_id,$info_content){
	$data['member_id']=$member_id;
	$data['info_content']=$info_content;
	$data['send_time']=time();
	$result=Db::table('lzh_info')->add($data);
	return $result;
}
//---验证身份证号码
function checkIdcode($id=''){
	$set = array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
	$ver = array('1','0','x','9','8','7','6','5','4','3','2');
	$arr = str_split($id);
	$sum = 0;
	for ($i = 0; $i < 17; $i++)
	{
		if (!is_numeric($arr[$i]))
		{
			return false;
		}
		$sum += $arr[$i] * $set[$i];
	}
	$mod = $sum % 11;
	if (strcasecmp($ver[$mod],$arr[17]) != 0)
	{
		return false;
	}
	return true;
}

function dis($slocal,$elocal){
	$durl='http://restapi.amap.com/v3/direction/walking?origin='.$slocal.'&destination='.$elocal.'&output=json&key='.config('GD');
	$result=json_decode(https_request($durl), true);
	$dis=$result['route']['paths'][0]['distance'];
	$dis=$dis==1?'0':$dis;
	return $dis;
}

function dis_2($slocal,$elocal){
	$durl='http://restapi.amap.com/v3/distance?origins='.$slocal.'&destination='.$elocal.'&output=json&key='.config('GD');
	$result=json_decode(https_request($durl), true);
	$dis=$result['results'][0]['distance'];
	$dis=$dis==1?'0':$dis;
	return $dis;
}

function auth_status_coach(){
	return array(
		0=>'未提交资料',1=>'已审核',2=>'审核中',3=>'未通过',
	);
}

function invoice_status(){
	return array(
		1=>'待付款',2=>'待邮寄',3=>'已邮寄',4=>'已取消'
	);
}
function ip_local_info($ip){
	$url = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
	$info = file_get_contents($url);
	return $info;
}

function order_type($type=''){
    $data = [1=>'专快车',2=>'出租车',3=>'城际快车',4=>'顺风车'];
    if(!empty($type)){
        return $data[$type];
    }else{
        return $data;
    }
}

function terminal($type=''){
    $data = [2=>'司机',1=>'乘客'];
    if(!empty($type)){
        return $data[$type];
    }else{
        return $data;
    }
}

//快车订单状态
function order_status($key='')
{
    $data = array(
        0=> "等待司机",5=>"司机取消",10=>"系统取消",12=>"有责取消",15=>"用户取消",16=>"司机抢单（预约）",17=>"去接乘客",18=>"到达上车点",30=>"已上车",40=>"已送达",45=>"已付款",50=>"已评价",
    );
    if($key !== ''){
        return $data[$key];
    }else{
        return $data;
    }

}

//将图片转为二进制流
function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = file_get_contents($image_file);
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

//丢失物品分类
function get_lost_type(){
    return array(
        1=>'电子产品类',2=>'箱包手袋',3=>'衣服鞋类',4=>'其他',
    );
}
//故障分类
function get_breakdown_type(){
    return array(
        1=>'频繁熄火',2=>'刹车不灵',3=>'灯光不亮',4=>'其他',
    );
}

//通过http向服务端发送消息
function socketToServer($data,$url='')
{
    include_once('socket_param.php');
    if($socket['login']==false){
        return true;
    }
    return https_request($socket['inner_http_use']?:$url,$data);
}

//截取指定长度字符串，中英混合皆可
function mb_truncate($str='',$start=0,$length=10,$tail='...',$encoding='utf8'){
    if(!$str){
        return false;
    }
    if(mb_strlen($str,'UTF-8')<=$length){
        return $str;
    }else{
        $substr = mb_substr($str, $start, $length, $encoding);
        return $substr.$tail;
    }
}

//成功提示
function ajax_success($msg=''){
    return json_encode(['code'=>1,'msg'=>$msg]);
}
//错误提示
function ajax_error($msg=''){
    return json_encode(['code'=>2,'msg'=>$msg]);
}

//司机背景资料调查
function infomationCurl($url,$data){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // post数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // post的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
    //执行请求
    $output = curl_exec($ch);
    return json_decode($output,true);
}

//获取用户手机号码
function userInfo($uid=''){
    $userInfo = Db::name('user')->where(["uid"=>$uid,'is_del'=>1])->find();
    return Security::decrypt($userInfo['user_phone']);
}

//处理进度
function progress(){
    return array(
        1 => '待处理', 2 => '处理中', 3 => '已处理'
    );
}

//二维数组去掉重复值
function array_unique_fd($array2D){
    foreach ($array2D as $v){
        $v=join(',',$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
        $temp[]=$v;
    }
    $temp=array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k => $v){
        $temp[$k]=explode(',',$v); //再将拆开的数组重新组装
    }
    return $temp;
}
//发送邮件
function send_email($data=[]){
    Vendor('phpmailer.phpmailer');
    $mail = new PHPMailer();                    //实例化
    $mail->IsSMTP();                            //启用SMTP
    $mail->Host         = 'smtp.qq.com';        //SMTP服务器 以126邮箱为例子
    $mail->Port         = 465;                  //邮件发送端口
    $mail->SMTPAuth     = true;                 //启用SMTP认证
    $mail->SMTPSecure   = "ssl";                // 设置安全验证方式为ssl
    $mail->CharSet      = "UTF-8";              //字符集
    $mail->Encoding     = "base64";             //编码方式
    $mail->Username     = '374270589@qq.com';   //你的邮箱
    $mail->Password     = 'dwkkvtcgeegdcbbg';   //你的密码
    $mail->Subject      = '资源鸟系统提示';     //邮件标题
    $mail->From         = '374270589@qq.com';   //发件人地址（也就是你的邮箱）
    $mail->FromName     = '资源鸟';             //发件人姓名
    $data = [['user_email'=>'1013384946@qq.com','content'=>'资源鸟，让一切变得简单，加qq群 623918245 畅聊']];
    $path = ROOT_PATH.'public\thumb\20190527163750172.jpg';
    if($data && is_array($data)){
        foreach ($data as $k=>$v){
            $mail->AddAddress($v['user_email'], "亲"); //添加收件人（地址，昵称）
            $mail->IsHTML(true); //支持html格式内容
            $mail->AddAttachment($path,'测试附件.jpg');
            $mail->Body = $v['content']; //邮件主体内容
            //发送成功就删除
            if ($mail->Send()) {
                echo "发送成功";
                return ['stauts'=>1,'msg'=>'发送成功'];
            }else{
                return ['status'=>0,'msg'=>'发送失败','code'=>'错误代码：Mailer Error '.$mail->ErrorInfo];
            }
        }
    }
}
function freeze_status($num){
    switch ($num){
        case 0:return "未冻结";break;
        case 1:return "已冻结";break;
    }
}

/**
 * 申诉状态
 */
function appealStatus($appealStatus)
{
    switch ($appealStatus) {
        case 0:
            return "待处理";
            break;
        case 1:
            return "申诉成功";
            break;

        default:
            return "申诉失败";
            break;
    }
}
/**
 * 申诉次数
 */
function appealNum($appealNum)
{
    switch ($appealNum) {
        case 1:
            return "申诉一次";
            break;
        default:
            return "申诉两次";
            break;
    }
}
/**
 * 封禁状态
 */
function forbidStatus($status)
{
    switch ($status) {
        case 1:
            return "永久封禁";
            break;
        case 2:
            return "未封禁";
            break;
        default:
            return "暂时封禁";
            break;
    }

}
